package com.util;

import com.alibaba.fastjson.JSON;
import com.bjsxt.dao.MenuMapper;
import com.bjsxt.entity.Menu;
import org.apache.ibatis.session.SqlSession;
import sun.applet.Main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 苏犇 on 2019/1/1. <br>
 */
public class MenuUtil {

    private static SqlSession sqlSession = null;
    private static List<Menu> allMenu;

    private static void init(List<Integer> powerIds) {
        sqlSession = MybatisUtil.getInstance().getSqlSession();
        allMenu = sqlSession.getMapper(MenuMapper.class).getMenusByPower(powerIds);
    }

    public static List<Map> getAllMenu(List<Integer> powerIds) {
        init(powerIds);
        List<Map> menuList = new ArrayList();
        for (Menu menu : allMenu) {
            if (menu.getPid() == 0) {
                Map map = new HashMap();
                map.put("id", menu.getId());
                map.put("text", menu.getMenuName());
                Map attr = new HashMap();
                attr.put("url", menu.getUrl());
                attr.put("menuStat", menu.getMenuStat());
                attr.put("pid", menu.getPid());
                map.put("attributes", attr);
                map.put("children", getChildMenu(menu.getId()));
                menuList.add(map);
            }
        }
        return menuList;
    }

    public static List<Map> getMenusWithoutUselessRoot(List<Integer> powerIds) {
        List<Map> list = getAllMenu(powerIds);
        List<Map> menus = new ArrayList();
        for (Map map : list) {
            if (((List) map.get("children")).size() != 0) {
                menus.add(map);
            }
        }
        return menus;
    }

    private static List<Map> getChildMenu(int pid) {
        List<Map> list = new ArrayList();
        for (Menu menu : allMenu) {
            if (menu.getPid() != 0) {
                if (menu.getPid() == pid) {
                    Map map = new HashMap();
                    map.put("id", menu.getId());
                    map.put("text", menu.getMenuName());
                    Map attr = new HashMap();
                    attr.put("url", menu.getUrl());
                    attr.put("menuStat", menu.getMenuStat());
                    attr.put("pid", menu.getPid());
                    map.put("attributes", attr);
                    map.put("children", getChildMenu(menu.getId()));
                    list.add(map);
                }
            }
        }
        return list;
    }

//    public static void main(String[] args) {
//        List list = getAllMenu();
//        System.out.println(JSON.toJSONString(list));
//    }
}
